# coding: utf-8
import socket
import threading
from threading import Event
import time

# 创建一个TCP连接
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9995))
s.listen(3)
# 输出提示语
print('Server is running on %s:%s' % ('127.0.0.1', 9999))
print('Waiting for connection...')


def speech(msg):
    from paddlespeech.server.bin.paddlespeech_client import TTSOnlineClientExecutor
    executor = TTSOnlineClientExecutor()
    executor(
        input=msg,
        server_ip="127.0.0.1",
        port=8092,
        protocol="http",
        spk_id=0,
        play=True)
    # msgs = []
    # msgs.append(msg)
    # print(msgs)
    # time.sleep(5)


def tcp_link(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    sock.send(b'true')  # 发送状态
    while True:
        r = sock.recv(1024)
        if not r or r.decode('utf-8') == 'exit':  # 结束连接指令
            break
        msg = r.decode('utf-8')
        speech_thread = threading.Thread(target=speech, args=(msg,))
        speech_thread.start()
        speech_thread.join()

        sock.send(('%s' % 'True').encode('utf-8'))
    sock.close()
    print('Client %s:%s is closed.' % addr)


while True:
    # 接受一个新连接:
    sock, addr = s.accept()
    print(addr)
    # 创建新线程来处理TCP连接:
    # 每个连接都必须创建新线程（或进程）来处理，否则，单线程在处理连接的过程中，无法接受其他客户端的连接
    t = threading.Thread(target=tcp_link, args=(sock, addr))
    t.start()
